﻿using Cache.Services.Interface;
using Enyim.Caching;
using Enyim.Caching.Memcached;
using System;

public class MemcachedCacheContext : ICacheContext
{
    private readonly IMemcachedClient _client;

    public MemcachedCacheContext(IMemcachedClient client)
    {
        _client = client ?? throw new ArgumentNullException(nameof(client));
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public override bool Exists(string key)
    {
        return _client.Get(key) != null;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public override T GetCache<T>(string key)
    {
        return _client.Get<T>(key);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="expire"></param>
    /// <returns></returns>
    public override bool SetCache<T>(string key, T value, DateTime expire)
    {
        return _client.Store(StoreMode.Set, key, value, expire - DateTime.Now);
    }

    /// <summary>
    /// 删除缓存
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public override bool RemoveCache(string key)
    {
        return _client.Remove(key);
    }

    /// <summary>
    /// 更新缓存名称
    /// </summary>
    /// <param name="key"></param>
    /// <param name="newKey"></param>
    /// <returns></returns>
    public override bool RenameKey(string key, string newKey)
    {
        // EnyimMemcachedCore does not support renaming keys directly.
        // You need to manually get the value, store it under the new key, and then delete the old key.
        var value = _client.Get(key);
        if (value != null)
        {
            _client.Store(StoreMode.Set, newKey, value);
            return _client.Remove(key);
        }
        return false;
    }
}
